package com.clinic.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.clinic.entity.gui.GuiPagination;
import com.clinic.entity.param.Index;

public final class CommonUtil {
	
	private static final Logger LOGGER = Logger.getLogger(CommonUtil.class);

	private static final String DAY_PATTERN = "dd";
	private static final String DATE_PATTERN = "yyyy-MM-dd";
	private static final String TIME_PATTERN = "h:mm";
	private static final String DATE_TIME_PATTERN = "yyyy-MM-dd h:mm";
	private static final SimpleDateFormat DAY_FORMAT = new SimpleDateFormat(DAY_PATTERN);
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DATE_PATTERN);
	private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat(TIME_PATTERN);
	private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat(DATE_TIME_PATTERN);

	public static String getTermStringByTerm(int n) {
		return n + "<sup>" + getTermSuffix(n) + "</sup> visit";
	}
	
	private static String getTermSuffix(int n) {
		if (n >= 11 && n <= 13) {
	        return "th";
	    }
	    switch (n % 10) {
	        case 1:  return "st";
	        case 2:  return "nd";
	        case 3:  return "rd";
	        default: return "th";
	    }
	}
	
	public static String getDayStringFormatByDate(Date date) {
		if (date != null) {
			return DAY_FORMAT.format(date);
		}
		return StringUtils.EMPTY;
	}
	
	public static String getDateStringFormatByDate(Date date) {
		if (date != null) {
			return DATE_FORMAT.format(date);
		}
		return StringUtils.EMPTY;
	}

	public static Date getDateByStringFormat(String strFormat) {
		if (StringUtils.isNotBlank(strFormat)) {
			try {
				return DATE_FORMAT.parse(strFormat);
			} catch (ParseException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
		return null;
	}
	
	public static Date getTimeByStringFormat(String strFormat) {
		if (StringUtils.isNotBlank(strFormat)) {
			try {
				return TIME_FORMAT.parse(strFormat);
			} catch (ParseException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
		return null;
	}
	
	public static String getTimeStringFormatByDate(Date date) {
		if (date != null) {
			return TIME_FORMAT.format(date);
		}
		return StringUtils.EMPTY;
	}
	
	public static Date getDateTimeByStringFormat(String dateTime) {
		if (StringUtils.isNotBlank(dateTime)) {
			try {
				return DATE_TIME_FORMAT.parse(dateTime);
			} catch (ParseException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
		return null;		
	}
	
	public static Date getDateTimeByDateAndTime(String date, String time) {
		String dateTime = date + " " + time;
		return ( CommonUtil.getDateTimeByStringFormat(dateTime));
	}
	
	public static int getDaysLeftfromToday(Date date) {
		Calendar oToday = Calendar.getInstance();
		if (date != null) {
			return getDiffDays(date, oToday.getTime());
		}
		return 0;
	}

	public static boolean isFutureDateTime(Date date) {
		Date todayDate = getTodayDate();
		if (date != null) {
			return (getDiffMilliSeconds(date, todayDate) / 1000) > 0;
		}
		return false;
	}
	
	public static boolean isTodayOrFutureDateTime(Date date) {
		Date todayDate = getTodayDate();
		if (date != null) {
			return (getDiffMilliSeconds(date, todayDate) / 1000) >= 0;
		}
		return false;
	}
	
	public static int getAgeByDob(Date dob) {
		return getDiffYears(dob, Calendar.getInstance().getTime());
	}
	
	public static int getDiffYears(Date first, Date last) {
	    Calendar a = getCalendar(first);
	    Calendar b = getCalendar(last);
	    int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
	    if (a.get(Calendar.MONTH) > b.get(Calendar.MONTH) || 
	        (a.get(Calendar.MONTH) == b.get(Calendar.MONTH) && a.get(Calendar.DATE) > b.get(Calendar.DATE))) {
	        diff--;
	    }
	    return diff;
	}
	
	public static int getDiffDays(Date first, Date last) {
	    long diff = getDiffMilliSeconds(first, last);
	    return (int) (diff / (24 * 60 * 60 * 1000));
	}

	public static long getDiffMilliSeconds(Date first, Date last) {
	    Calendar a = getCalendar(first);
	    Calendar b = getCalendar(last);
	    
	    long milliseconds1 = a.getTimeInMillis();
	    long milliseconds2 = b.getTimeInMillis();
	    
	    return milliseconds1 - milliseconds2;
	}
	
	public static Calendar getCalendar(Date date) {
	    Calendar cal = Calendar.getInstance();
	    cal.setTime(date);
	    return cal;
	}
	
	public static Date getTodayDate() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		return cal.getTime();
	}
	
	
	public static Date getStartDateOfMonthByDate(Date date) {
		Calendar cal = Calendar.getInstance();  
		cal.setTime(date);
		
		cal.add(Calendar.MONTH, 0);  
		cal.set(Calendar.DAY_OF_MONTH, 0);  
		cal.add(Calendar.DATE, 1);
		
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		return cal.getTime(); 
	}
	
	public static Date getEndDateOfMonthByDate(Date date) {
		Calendar cal = Calendar.getInstance();  
		cal.setTime(date); 
		
        cal.add(Calendar.MONTH, 1);  
        cal.set(Calendar.DAY_OF_MONTH, 1);  
        cal.add(Calendar.DATE, -1);
        
        cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		return cal.getTime(); 
	}
	
	public static List<Date> getListOfDaysBetweenTwoDates(Date startDate, Date endDate) {
	    List<Date> result = new ArrayList<Date>();
	    Calendar start = Calendar.getInstance();
	    start.setTime(startDate);
	    Calendar end = Calendar.getInstance();
	    end.setTime(endDate);
	    end.add(Calendar.DAY_OF_YEAR, 1); //Add 1 day to endDate to make sure endDate is included into the final list
	    while (start.before(end)) {
	        result.add(start.getTime());
	        start.add(Calendar.DAY_OF_YEAR, 1);
	    }
	    return result;
	}
	
	public static Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date); //setTime method used to set date
        cal.add(Calendar.DATE, days); //add next date to the calendar
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		
        return cal.getTime();
    }
	
	public static String trim(String str) {
		return StringUtils.trim(str).replaceAll("\\s+", StringUtils.EMPTY);
	}
	
	public static Index getIndexBypage(int page) {
		int oPage = ((page-1) < 0) ? 0 : (page-1);
		Index index = new Index(oPage*(Index.DEFAULT_MAX_ITEMS), Index.DEFAULT_MAX_ITEMS);
		return index;
	}
	
	public static GuiPagination getPaginationInfo(int page, int total) {
		GuiPagination result = new GuiPagination();
		int pageCount = Index.DEFAULT_MAX_ITEMS;
		int noOfPages = (int) Math.ceil((double)total/pageCount);
		result.setTotalCount(total);
		result.setNoOfPages(noOfPages);
		result.setActivePage(page > 0 ? page : 1);
		result.setFirstPage(1);
		result.setLastPage(noOfPages);		
		result.setPrevPage((page-1) > 0 ? (page-1) : 1);
		result.setNextPage((page+1) < noOfPages ? (page+1) : noOfPages);
		
		return result;
	}
	
	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();
//		System.out.println(getTimeStringFormatByDate(cal.getTime()));
//		System.out.println(getDateByStringFormat("2012-05-29 6.30"));
//		System.out.println(getDateTimeByStringFormat("2012-05-29 6:30"));
		System.out.println(getStartDateOfMonthByDate(cal.getTime()));
		System.out.println(getEndDateOfMonthByDate(cal.getTime()));
	} 

}
